<template>
  <div class="bg-white rounded-2xl shadow-2xl p-8">
    <!-- 标题切换 -->
    <div class="text-center mb-8">
      <h2 class="text-3xl font-bold text-gray-800 mb-2">
        {{ isLoginMode ? "欢迎回来" : "加入我们" }}
      </h2>
      <p class="text-gray-600">
        {{ isLoginMode ? "登录到您的账户" : "创建一个新的账户" }}
      </p>
    </div>
    <!-- 切换按钮 -->
    <div class="flex mb-6 p-1 bg-gray-100 rounded-lg">
      <button
        @click="switchToLogin"
        :class="[
          'flex-1 py-2 px-4 rounded-md text-sm font-medium transition-all duration-200',
          isLoginMode
            ? 'bg-white text-bsr shadow-sm'
            : 'text-gray-600 hover:text-gray-800',
        ]"
      >
        登录
      </button>
      <button
        @click="switchToRegister"
        :class="[
          'flex-1 py-2 px-4 rounded-md text-sm font-medium transition-all duration-200',
          !isLoginMode
            ? 'bg-white text-bsr shadow-sm'
            : 'text-gray-600 hover:text-gray-800',
        ]"
      >
        用户名密码注册
      </button>
    </div>

    <!-- 登录表单组件 -->
    <AuthLoginForm
      v-if="isLoginMode"
      ref="loginFormRef"
      :loading="loading"
      :error-message="errorMessage"
      :captcha-image="captchaImage"
      @send-code="sendCode"
      @refresh-captcha="refreshCaptcha"
      @login="handleLogin"
    />

    <!-- 注册表单组件 -->
    <AuthRegisterForm
      v-else
      ref="registerFormRef"
      :loading="loading"
      :error-message="errorMessage"
      :captcha-image="captchaImage"
      @send-code="sendCode"
      @refresh-captcha="refreshCaptcha"
      @register="handleRegister"
    />
  </div>
</template>

<script setup lang="ts">
import { nextTick } from 'vue';
const { login, register, getChaptcha } = useAuth();
const { success: toastSuccess } = useToast();
const loadingStore = useLoadingStore();
// 表单状态
const isLoginMode = ref(true);
const loading = ref(false);
const errorMessage = ref("");

// 验证码图片
const captchaImage = ref("");

// 组件引用
const loginFormRef = ref();
const registerFormRef = ref();

// 切换到登录模式
const switchToLogin = () => {
  isLoginMode.value = true;
  errorMessage.value = "";
  captchaImage.value = ""; 
  registerFormRef.value?.resetForm?.();
};

// 切换到注册模式
const switchToRegister = () => {
  isLoginMode.value = false;
  errorMessage.value = "";
  captchaImage.value = ""; 
  loginFormRef.value?.resetForm?.();
};

const sendCode = async (username: string) => {
  if (!username) {
    errorMessage.value = "请先填写用户名再获取验证码";
    return;
  }
  try {
    errorMessage.value = "";
    loadingStore.show();
    const result = await getChaptcha();
    if (result.errCode === 0) {
      captchaImage.value = `${result.captchaBase64}`;
    } else {
      throw new Error(result?.message || "获取验证码失败");
    }
  } catch (err: any) {
    errorMessage.value = err?.message || "验证码获取失败";
  } finally {
    loadingStore.hide();
  }
};

// 刷新验证码
const refreshCaptcha = async () => {
  if (isLoginMode.value) {
    // 登录模式刷新，使用登录表单的用户名
    const username = loginFormRef.value?.loginForm?.username || "";
    if (username) {
      await sendCode(username);
    }
  } else {
    // 注册模式刷新，使用注册表单的用户名
    const username = registerFormRef.value?.registerForm?.username || "";
    if (username) {
      await sendCode(username);
    }
  }
};

// 处理登录
const handleLogin = async (formData: {
  username: string;
  password: string;
  code: string;
}) => {
  loading.value = true;
  errorMessage.value = "";
  try {
    const { success, message } = await login(formData);
    if (success) {
      errorMessage.value = "";
      loginFormRef.value?.resetForm?.();
    } else {
      errorMessage.value = message;
    }
  } catch (error: any) {
    errorMessage.value = error.message || "登录失败";
  } finally {
    loading.value = false;
  }
};

// 处理注册
const handleRegister = async (formData: {
  username: string;
  password: string;
  code: string;
}) => {
  loading.value = true;
  errorMessage.value = "";
  try {
    const { success, message } = await register(formData);
    if (success) {
      // 等待下一个渲染周期并确保在客户端环境执行，以避免 SSR 渲染时机导致的提示丢失
      if (import.meta.client) {
        await nextTick();
        toastSuccess("注册成功");
      }
      errorMessage.value = "";
      registerFormRef.value?.resetForm?.();
      // 自动切换到登录模式
      isLoginMode.value = true;
    } else {
      refreshCaptcha()
      errorMessage.value = message;
    }
  } catch (error: any) {
    refreshCaptcha()
    errorMessage.value = error.message || "注册失败";
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 自定义动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.bg-white {
  animation: fadeIn 0.5s ease-out;
}

/* 输入框焦点效果 */
input:focus {
  box-shadow: 0 0 0 3px rgba(194, 48, 28, 0.1);
}

/* 按钮悬停效果 */
button {
  transition: all 0.2s ease;
}
</style>
